package com.yale.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by yale on 2017/10/20.
 */
public class FileUpload extends ActionSupport {

    //uploadContentType=控件名+ContentType
    //uploadFileName=控件名+FileName

       /*        <s:form action="upload.action" enctype="multipart/form-data" method="post">
               <s:file name="upload" label="选择文件"/>
               </s:form>
       */

    //保存到服务器的目录,对应的struts.xml中的配置文件中配置的savePath,通过 get获得
    private String savePath;
    //文件类型
    private String uploadContentType;
    //文件名
    private String uploadFileName;
    //上传文件
    private File upload;

    @Override
    public String execute() throws Exception {
        System.out.println("文件路径:"+upload.getPath());
        System.out.println("保存路径:"+this.getSavePath());
        System.out.println("文件名称:"+this.getUploadFileName());
        //输入流进行文件的读取
        InputStream is = new FileInputStream(this.upload);

        //将文件写出到服务器上
        FileOutputStream fos = new FileOutputStream(this.getSavePath()+"/"+this.getUploadFileName());
        int r = -1;
        while((r = is.read()) != -1){
            fos.write(r);
        }

        return Action.SUCCESS;
    }


    public String getSavePath() {
        //获取绝对路径，不然服务器报500错误
        String applicationPath =System.getProperty("user.dir");
        applicationPath =applicationPath.replace("\\","/");
//        return ServletActionContext.getServletContext().getRealPath(savePath);
        return applicationPath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    public String getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public String getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }


}
